<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="编号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间"
        />
      </el-form-item>
      <el-form-item label="采购截止日期" prop="finishTime">
        <el-date-picker
          v-model="queryParams.finishTime"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采购截止日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:plan:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:plan:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleCheck"
        >详情</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:plan:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['erp:plan:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购截止日期" align="center" prop="finishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否完成 0否1是" align="center" prop="isFinish" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['erp:purchase:add']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAddpurchase(scope.row)"
          >生成采购单</el-button>
          <el-button
            v-hasPermi="['erp:plan:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheck(scope.row)"
          >详情</el-button>
          <el-button
            v-hasPermi="['erp:plan:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加采购计划 -->
    <el-dialog title="添加采购计划" :visible.sync="openadd" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购截止日期" prop="finishTime">
          <el-date-picker
            v-model="form.finishTime"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择采购截止日期"
          />
        </el-form-item>
        <el-divider content-position="center">采购计划物品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <div>
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddBPlanItem">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBPlanItem">删除</el-button>
            </el-col>
          </div>

        </el-row>
        <el-table ref="bPlanItem" :data="addPlanItemVoList" :row-class-name="rowBPlanItemIndex" @selection-change="handleBPlanItemSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="150" />

          <el-table-column label="物品名称" prop="itemId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.itemId" placeholder="物品名称">
                <el-option
                  v-for="item in options"
                  :key="item.itemId"
                  :label="item.itemName"
                  :value="item.itemId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="计划数量" prop="planNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.planNum" placeholder="请输入计划数量" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 采购计划详情 -->
    <el-dialog title="采购计划详情" :visible.sync="openform" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购截止日期" prop="finishTime">
          <el-date-picker
            v-model="form.finishTime"
            disabled
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择采购截止日期"
          />
        </el-form-item>
        <el-divider content-position="center">采购计划物品信息</el-divider>
        <el-table ref="bPlanItem" :data="addPlanItemVoList" :row-class-name="rowBPlanItemIndex" @selection-change="handleBPlanItemSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="150" />
          <div>
            <el-table-column label="物品名称" align="center" prop="itemName" width="150" />
            <el-table-column label="计划数量" align="center" prop="planNum" width="150" />
          </div>

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加采购单 -->
    <el-dialog title="添加采购单" :visible.sync="openpurchase" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购截止日期" prop="finishTime">
          <el-date-picker
            v-model="form.finishTime"
            disabled
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择采购截止日期"
          />
        </el-form-item>
        <el-form-item label="总价" prop="finishTime">
          {{ sumCos }}
        </el-form-item>
        <el-divider content-position="center">采购计划物品信息</el-divider>
        <el-table ref="bPlanItem" :data="addPurchaseForm" :row-class-name="rowBPlanItemIndex" @selection-change="handleBPlanItemSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="150" />
          <el-table-column label="物品名称" align="center" prop="itemName" width="150" />
          <el-table-column label="计划数量" align="center" prop="planNum" width="150" />
          <el-table-column label="供应商" prop="supName" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.supId" placeholder="选择供应商">
                <el-option
                  v-for="item in purchaseoptions"
                  :key="item.supId"
                  :label="item.supName"
                  :value="item.supId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物品单价" prop="cost" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cost" placeholder="请输入计划数量" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">生 成</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlanItems, getPlan, delPlan, addPlan } from '@/api/erp/plan/plan'
import { addPurchase } from '@/api/erp/purchase/purchase.js'
import { listSupplier } from '@/api/erp/supplier/supplier.js'

export default {
  name: 'Plan',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBPlanItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购计划表格数据
      planList: [],
      // 采购计划物品表格数据
      addPlanItemVoList: [],
      // 添加采购单的表格数据
      addPurchaseForm: [],
      // 是否显示弹出层
      openadd: false,
      openform: false,
      openpurchase: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        createTime: null,
        finishTime: null
      },
      purchaseoptions: [],
      options: [],
      houseoptions: [],
      value: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        finishTime: [
          { required: true, message: '采购截止日期不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    sumCos() {
      var total = 0
      this.addPurchaseForm.forEach(item => {
        total += item.planNum * item.cost
      })
      return total
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    getPlanItems().then(res => {
      res.data.forEach(element => {
        this.options.push({
          itemId: element.id,
          itemName: element.itemName
        })
      })
    })
  },
  methods: {
    /** 查询采购计划列表 */
    getList() {
      this.loading = true
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.openadd = false
      this.openform = false
      this.openpurchase = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        finishTime: null,
        isPurchase: null,
        isFinish: null,
        isDelete: null
      }
      this.addPlanItemVoList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.openform = false
      this.openadd = true
    },
    // 生成采购单
    handleAddpurchase(row) {
      this.reset()
      const id = row.id || this.ids
      this.purchaseoptions = []
      getPlan(id).then(response => {
        this.form = response.data
        this.addPurchaseForm = response.data.planItemList
        this.openpurchase = true
      })
      listSupplier().then(res => {
        res.rows.forEach(item => {
          this.purchaseoptions.push({
            supId: item.id,
            supName: item.supName
          })
        })
      })
    },
    /** 详情按钮操作 */
    handleCheck(row) {
      this.reset()
      const id = row.id || this.ids

      getPlan(id).then(response => {
        this.form = response.data
        this.addPlanItemVoList = response.data.planItemList
        this.openform = true
        this.openadd = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.addPlanItemVoList = this.addPlanItemVoList
          if (this.form.id != null) {
            if (this.openpurchase) {
              var total = 0
              this.addPurchaseForm.forEach(item => {
                total = total + item.planNum * item.cost
              })
              var itemArr = []
              this.addPurchaseForm.forEach(item => {
                itemArr.push({
                  cost: item.cost * 1,
                  itemId: item.id * 1,
                  purchaseNum: item.planNum * 1,
                  supplierId: item.supId * 1
                })
              })
              console.log(itemArr)
              addPurchase({
                addPurchaseItemVoList: itemArr,
                planId: this.form.id * 1,
                sumCos: total * 1
              }).then(res => {
                this.openpurchase = false
              })
            }
            this.openform = false
            this.openadd = false
          } else {
            this.form.addPlanItemVoList.forEach(item => {
              item.planNum = item.planNum * 1
            })
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.openform = false
              this.openadd = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除采购计划编号为"' + ids + '"的数据项？').then(function() {
        return delPlan(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 采购计划物品序号 */
    rowBPlanItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 采购计划物品添加按钮操作 */
    handleAddBPlanItem() {
      const obj = {}
      obj.itemId = ''
      obj.planNum = 0
      this.addPlanItemVoList.push(obj)
    },
    /** 采购计划物品删除按钮操作 */
    handleDeleteBPlanItem() {
      if (this.checkedBPlanItem.length === 0) {
        this.$modal.msgError('请先选择要删除的采购计划物品数据')
      } else {
        const addPlanItemVoList = this.addPlanItemVoList
        const checkedBPlanItem = this.checkedBPlanItem
        this.addPlanItemVoList = addPlanItemVoList.filter(function(item) {
          return checkedBPlanItem.indexOf(item.index) === -1
        })
      }
    },
    /** 复选框选中数据 */
    handleBPlanItemSelectionChange(selection) {
      this.checkedBPlanItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
